const run = require('parallel-webpack').run;
const path = require('path');
const fs = require('fs');
const webpack = require('webpack');
const devConfig = require('./lib/config/webpack.config.dev');
const ssrConfig = require('./lib/config/webpack.config.ssr');
const prodConfig = require('./lib/config/webpack.config.prod');
const cubeConfig = require('./lib/config/webpack.config.cube');

const _build = function (config, callback) {
  return new Promise((resolve, reject) => {
    webpack(config, (err, stats) => {
      if (err) {
        console.error(err);
        return reject(err);
      }
      console.log(
        stats.toString({
          chunks: false, // 使构建过程更静默无输出
          colors: true, // 在控制台展示颜色
        }),
      );
      resolve(stats);
    });
  });
};

const getPageConfig = function (data, env) {
  const configPath = path.join(data.gitLoacl, 'page-config.js');
  let config = {};
  if (fs.existsSync(configPath)) config = require(configPath)(env);
  const postcssConfig = path.join(data.gitLoacl, 'postcss.config.js');
  if (fs.existsSync(postcssConfig)) {
    config.postcssConfig = require(postcssConfig);
  }
  const babelConfig = path.join(data.gitLoacl, 'babel.config.js');
  if (fs.existsSync(babelConfig)) {
    config.babelConfig = require(babelConfig);
  }
  return config;
};

const buildConfig = {
  dev: async function (data) {
    const config = await devConfig(data, getPageConfig(data, 'development'));
    return await _build(config);
  },
  ssr: async function (data) {
    const config = await ssrConfig(data, getPageConfig(data, 'development'));
    return await _build(config);
  },
  prod: async function (data) {
    const config = await prodConfig(data, getPageConfig(data, 'production'));
    const a = await _build(config);
    return a;
  },
  cube: async function (data) {
    const config = cubeConfig(data);
    const a = await _build(config);
    return a;
  },
};

module.exports = buildConfig;
